package com.example.sql;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.telephoneBook.LoginActivity;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;

public class HttpThread extends Thread{
	private String url;
	private Context context;
	private SqlHelp dbhelp;
	private SQLiteDatabase db;
	private Handler handler;
	public HttpThread (String url,Context context){
		this.url = url;
		this.context = context;
		
		
	}
	
	public void run(){
		try {
			URL httpUrl = new URL(url);
			HttpURLConnection conn;
			try {
				conn = (HttpURLConnection)httpUrl.openConnection();
				conn.setReadTimeout(5000);
				conn.setRequestMethod("GET");
				StringBuffer sb = new StringBuffer();
				BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
				String str;
				
				while ((str=reader.readLine())!=null) {
					sb.append(str);
				}
				String sbString = sb.toString();
				parseJson(sbString);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void parseJson(String json) {
		try {
			JSONObject object =new JSONObject(json);
			
		
				JSONArray pnData = object.getJSONArray("13移动互联3-2班");
				if(pnData != null){
					System.out.println("读取成功");
				}
				PNOperator pno = new PNOperator(context);
				dbhelp = new SqlHelp(context, SqlHelp.DBName);
				db = dbhelp.getReadableDatabase();
				for (int i = 0; i < pnData.length(); i++) {
					PNBean pnBean = new PNBean();
					JSONObject person = pnData.getJSONObject(i);
					String name = person.getString("name");
					String phonenumber = person.getString("phonenumber");
					String shortnumber = person.getString("shortnumber");
					pnBean.setName(name);
					pnBean.setPhoneNumber(phonenumber);
					pnBean.setShortNumber(shortnumber);
					Cursor cursor = db.query(SqlHelp.TableNumber, null,
							"name=? and phonenumber=? and shortnumber=?", new String[] {
									name,phonenumber,shortnumber },
							null, null, null);
					
					int a = cursor.getCount();
					if( a == 0 ){
						pno.insert(pnBean);
						cursor.close();
					}else {
						
						cursor.close();
					}
				}
				db.close();
				
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
